<template>
  <Transition name="toast" appear>
    <div
      v-if="visible"
      class="copy-toast fixed top-4 left-1/2 transform -translate-x-1/2 z-9999 px-6 py-3 rounded-lg shadow-xl pointer-events-auto flex items-center space-x-2"
      :class="toastClass"
    >
      <!-- 图标 -->
      <svg class="w-5 h-5 shrink-0" fill="currentColor" viewBox="0 0 20 20">
        <!-- 成功图标 -->
        <path
          v-if="type === 'success'"
          fill-rule="evenodd"
          d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z"
          clip-rule="evenodd"
        />
        <!-- 错误图标 -->
        <path
          v-else-if="type === 'error'"
          fill-rule="evenodd"
          d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
          clip-rule="evenodd"
        />
      </svg>

      <!-- 文本 -->
      <span class="font-medium text-sm">{{ message }}</span>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'

interface Props {
  message: string
  type: 'success' | 'error'
  duration?: number // 默认2000ms
}

const props = withDefaults(defineProps<Props>(), {
  duration: 2000,
})

const visible = ref(false)
let timer: number | null = null

const toastClass = computed(() => {
  if (props.type === 'success') {
    return 'bg-green-500 text-white'
  } else {
    return 'bg-red-500 text-white'
  }
})

onMounted(() => {
  // 立即显示
  visible.value = true

  // 设置自动隐藏
  timer = window.setTimeout(() => {
    visible.value = false
  }, props.duration)
})

onUnmounted(() => {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
})
</script>

<style scoped>
/* 淡入淡出动画 */
.toast-enter-active {
  transition: all 0.3s ease-out;
}

.toast-leave-active {
  transition: all 0.3s ease-in;
}

.toast-enter-from {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px) scale(0.95);
}

.toast-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(-20px) scale(0.95);
}

/* 确保在所有设备上都能正常显示 */
.copy-toast {
  min-width: 200px;
  max-width: 90vw;
  text-align: center;

  /* 确保在移动设备上也能正常显示 */
  @media (max-width: 640px) {
    min-width: 150px;
    padding: 0.75rem 1rem;
    font-size: 0.875rem;
  }
}

/* 高对比度模式支持 */
@media (prefers-contrast: high) {
  .copy-toast {
    border: 2px solid;
  }

  .copy-toast.bg-green-500 {
    border-color: #065f46;
  }

  .copy-toast.bg-red-500 {
    border-color: #991b1b;
  }
}

/* 减少动画偏好支持 */
@media (prefers-reduced-motion: reduce) {
  .toast-enter-active,
  .toast-leave-active {
    transition: none;
  }

  .toast-enter-from,
  .toast-leave-to {
    transform: translateX(-50%);
  }
}
</style>
